﻿using System.Windows;
using DSPL.Services;
using DSPL.Contracts;
using DSPL.Common;
using System.Data;
using DSPL.Services.Services;
using DSPL.Contracts.Common;
using DSPL.Contracts.ViewModel;
using DSPL.Contracts.Command;
using DSPL.Finac.Common;
using System;
using System.Windows.Input;
using System.Collections.Generic;
using DSPL.Contracts.Interfaces;
using DSPL.Common.Classes;
using DSPL.Services.Rules;
using System.Linq;

namespace DSPL.Finac.ViewModel
{
    public class GoodReceiveNoteViewModel : BaseViewModel
    {
        private bool isReferenceNoFocused;
        private bool isPurchaseOrderNoFocused;
        private bool isCurrencyCodeFocused;
        private bool isSupplierCodeFocused;
        private bool isLocationCodeFocused;
        private bool isCostCodeFocused;
        private bool isExchangeRateFocused;
        private bool isTransactionDateFocused;
        private bool isPurchaseOrderNoMandatory;
        private bool isCurrencyCodeEnabled;
        private bool isExchangeRateEnabled;
        private bool isEditButtonEnabled;
        private bool isRemarksEnabled;
        private bool isTaxComcodeEnabled;
        private bool isTaxComCodeFocused;
        private DataRow drItemRow;
        private ICommand refreshCurrencyData;
        private ICommand currencyCodeLostFocus;
        private ICommand calculation;
        private ICommand itemCodeLostFocus;
        private int _txn0002ConCode;
        private int _txn0001ConCode;
        private int _txn0004ConCode;
        private int _txn0003ConCode;
        private int _txn0005ConCode;
        private int _txn0016ConCode;
        private int itemRowIndex;        
        private string _refNoFilterExpression;        
        private Visibility isPurchaseOrderNoVisible;
        private bool isPurchaseOrderNoEnabled;
        private DataTable _dtGrnTax;
        private DataTable _dtGrnImExp;
        private DataTable _dtImpExp;
        private DataTable _dtCCrNote;
        private DataTable _dtGrnImpExp;
        private DateTime _chkTxnDate;
        private DataTable _dtPoHeader;
        private bool _hasHedSaveFailed;
        private Modes _txnTransactionType;
        private string  _previousItemCode;

        #region Define properties

        public bool IsReferenceNoFocused
        {
            get { return isReferenceNoFocused; }
            set
            {
                isReferenceNoFocused = value;
                this.OnPropertyChanged("IsReferenceNoFocused");

            }

        }
        public bool IsPurchaseOrderNoFocused
        {
            get { return isPurchaseOrderNoFocused; }
            set
            {
                isPurchaseOrderNoFocused = value;
                this.OnPropertyChanged("IsPurchaseOrderNoFocused");
            }
        }

        public bool IsCurrencyCodeFocused
        {
            get { return isCurrencyCodeFocused; }
            set
            {
                isCurrencyCodeFocused = value;
                this.OnPropertyChanged("IsCurrencyCodeFocused");

            }
        }

        public bool IsSupplierCodeFocused
        {
            get { return isSupplierCodeFocused; }
            set
            {
                isSupplierCodeFocused = value;
                this.OnPropertyChanged("IsSupplierCodeFocused");

            }
        }

        public bool IsLocationCodeFocused
        {
            get { return isLocationCodeFocused; }
            set
            {
                isLocationCodeFocused = value;
                this.OnPropertyChanged("IsLocationCodeFocused");

            }
        }

        public bool IsCostCodeFocused
        {
            get { return isCostCodeFocused; }
            set
            {
                isCostCodeFocused = value;
                this.OnPropertyChanged("IsCostCodeFocused");

            }
        }

        public bool IsExchangeRateFocused
        {
            get { return isExchangeRateFocused; }
            set
            {
                isExchangeRateFocused = value;
                this.OnPropertyChanged("IsExchangeRateFocused");

            }
        }

        public bool IsTaxComCodeFocused
        {
            get { return isTaxComCodeFocused; }
            set
            {
                isTaxComCodeFocused = value;
                this.OnPropertyChanged("IsTaxComCodeFocused");

            }
        }

        public bool IsTransactionDateFocused
        {
            get { return isTransactionDateFocused; }
            set
            {
                isTransactionDateFocused = value;
                this.OnPropertyChanged("IsTransactionDateFocused");

            }
        }


        public DataRow ItemSelectedRow
        {
            get
            {
                return drItemRow;
            }
            set
            {
                drItemRow = value;
                OnPropertyChanged("ItemSelectedRow");
            }
        }

        public string RefNoFilterExpression
        {
            get
            {
                return _refNoFilterExpression;
            }
            set
            {
                _refNoFilterExpression = value;
                OnPropertyChanged("RefNoFilterExpression");
            }
        }

        public Visibility IsPurchaseOrderNoVisible
        {
            get
            {
                return isPurchaseOrderNoVisible;
            }
            set
            {
                isPurchaseOrderNoVisible = value;
                OnPropertyChanged("IsPurchaseOrderNoVisible");
            }
        }

        public bool IsPurchaseOrderNoMandatory
        {
            get
            {
                return isPurchaseOrderNoMandatory;
            }
            set
            {
                isPurchaseOrderNoMandatory = value;
                OnPropertyChanged("IsPurchaseOrderNoMandatory");
            }
        }

        public bool IsCurrencyCodeEnabled
        {
            get
            {
                return isCurrencyCodeEnabled;
            }

            set
            {
                isCurrencyCodeEnabled = value;
                this.OnPropertyChanged("IsCurrencyCodeEnabled");
            }
        }


        public bool IsExchangeRateEnabled
        {
            get
            {
                return isExchangeRateEnabled;
            }

            set
            {
                isExchangeRateEnabled = value;
                this.OnPropertyChanged("IsExchangeRateEnabled");
            }
        }


        public bool IsPurchaseOrderNoEnabled
        {
            get
            {
                return isPurchaseOrderNoEnabled;
            }

            set
            {
                isPurchaseOrderNoEnabled = value;
                this.OnPropertyChanged("IsPurchaseOrderNoEnabled");
            }
        }

        public bool IsRemarksEnabled
        {
            get
            {
                return isRemarksEnabled;
            }

            set
            {
                isRemarksEnabled = value;
                this.OnPropertyChanged("IsRemarksEnabled");
            }
        }

        public bool IsTaxComcodeEnabled
        {
            get
            {
                return isTaxComcodeEnabled;
            }

            set
            {
                isTaxComcodeEnabled = value;
                this.OnPropertyChanged("IsTaxComcodeEnabled");
            }
        }

        public int ItemRowIndex
        {
            get
            {
                return itemRowIndex;
            }
            set
            {
                itemRowIndex = value;
                OnPropertyChanged("ItemRowIndex");
            }
        }

        #endregion


        #region Constructor

        public GoodReceiveNoteViewModel()
            : base()
        {
            MessageTitle = "Good Receive Note ";
           
        }

        #endregion

        # region Commands

        public ICommand RefreshCurrencyData
        {
            get
            {
                if (this.refreshCurrencyData == null)
                {
                    this.refreshCurrencyData = new RelayCommand(RefreshCurrencyDataExecuted);
                }
                return this.refreshCurrencyData;
            }
        }

        public ICommand Calculation
        {
            get
            {
                if (this.calculation == null)
                {
                    this.calculation = new RelayCommand(CalculateAmountsExecuted);
                }
                return this.calculation;
            }
        }


        public ICommand CurrencyCodeLostFocus
        {
            get
            {
                if (this.currencyCodeLostFocus == null)
                {
                    this.currencyCodeLostFocus = new RelayCommand(CurrencyCodeLostFocusExecuted);
                }
                return this.currencyCodeLostFocus;
            }
        }

        public ICommand ItemCodeLostFocus
        {
            get
            {
                if (this.itemCodeLostFocus == null)
                {
                    this.itemCodeLostFocus = new RelayCommand(ItemCodeLostFocusExecuted);
                }
                return this.itemCodeLostFocus;
            }
        }

        #endregion
        /// <summary>
        /// Validate mandatory data before save
        /// </summary>
        /// <param name="obj"></param>
        protected override void PreDataValidateExecuted(object obj)
        {
            IsReferenceNoFocused = false;
            IsPurchaseOrderNoFocused = false;
            IsCurrencyCodeFocused = false;
            IsSupplierCodeFocused = false;
            IsLocationCodeFocused = false;
            IsCostCodeFocused = false;
            IsExchangeRateFocused = false;
            IsTransactionDateFocused = false;

            var messageService = new MessageService();
            var masterReadService = new MasterReadService();
            var transactionService = new TransactionReadService();

            if (FormMode != Modes.New)
            {
                if (string.IsNullOrEmpty(CurrentRow["RefNo"].ToString().Trim()))
                {
                    messageService.ShowMessage(MessageText.ReferenceNoNotEmpty, MessageTitle, MessageType.InfoOK);
                    IsReferenceNoFocused = true;
                    this.IsValid = false;
                    return;
                }
            }


            if (_txn0001ConCode == 1)
            {
                if (CurrentRow["PoPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["PoPk"]) == 0)
                {
                    messageService.ShowMessage(MessageText.PoNoGrnNotEmpty, MessageTitle, MessageType.InfoOK);
                    IsPurchaseOrderNoFocused = true;
                    this.IsValid = false;
                    return;
                }
            }

            if (CurrentRow["TxnDate"] == DBNull.Value)
            {
                messageService.ShowMessage(MessageText.TransactionDateNotEmpty, MessageTitle, MessageType.InfoOK);
                IsTransactionDateFocused = true;
                this.IsValid = false;
                return;
            }
            else
            {
                if (CurrentRow["PoPk"] != DBNull.Value && Convert.ToInt32(CurrentRow["PoPk"]) != 0)
                {
                    if (_chkTxnDate > Convert.ToDateTime(CurrentRow["TxnDate"]))
                    {
                        messageService.ShowMessage(MessageText.GrnDateLessThanPoDate, MessageTitle, MessageType.InfoOK);
                        IsTransactionDateFocused = true;
                        this.IsValid = false;
                    }
                }

                var stockRules = new StockRulesService();
                if (!stockRules.ValidateStockTransactionDate(Convert.ToDateTime(CurrentRow["TxnDate"]), CurrentRow["RefNo"].ToString().Trim(), BlockBackDatedTransaction, ReportGroup))
                {
                    IsTransactionDateFocused = true;
                    this.IsValid = false;
                    return;
                }
            }

            if (CurrentRow["CurPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["CurPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.CurrencyCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsCurrencyCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["CurRate"] == DBNull.Value || Convert.ToInt32(CurrentRow["CurRate"]) == 0)
            {
                messageService.ShowMessage(MessageText.CurrencyRateNotZero, MessageTitle, MessageType.InfoOK);
                IsExchangeRateFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["SupplierPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["SupplierPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.SupplierNotEmpty, MessageTitle, MessageType.InfoOK);
                IsSupplierCodeFocused = true;
                this.IsValid = false;
                return;
            }

            else
            {
                if (!masterReadService.IsSupplierActive(Convert.ToInt32(CurrentRow["SupplierPk"])))
                {
                    messageService.ShowMessage(MessageText.SupplierNotActive, MessageTitle, MessageType.InfoOK);
                    IsSupplierCodeFocused = true;
                    this.IsValid = false;
                    return;
                }
            }

            if (CurrentRow["LocationPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["LocationPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.LocationNotEmpty, MessageTitle, MessageType.InfoOK);
                IsLocationCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["CostPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["CostPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.CostCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsCostCodeFocused = true;
                this.IsValid = false;
                return;
            }
            

            if (CurrentRow["TaxComPk"] != DBNull.Value && Convert.ToInt32(CurrentRow["TaxComPk"]) != 0)
            {
                if (!masterReadService.IsTaxCombinationActive(Convert.ToInt32(CurrentRow["TaxComPk"])))
                {
                    messageService.ShowMessage(MessageText.TaxCombinationNotActive, MessageTitle, MessageType.InfoOK);
                    IsTaxComCodeFocused = true;
                    this.IsValid = false;
                    return;
                }
            }

            if (!CheckItemStatus())
            {
                this.IsValid = false;
                return;
            }

            if (!CheckTaxSCombinationStatus())
            {
                this.IsValid = false;
                return;
            }

            
            if ((CurrentRow["PoPk"] != DBNull.Value && Convert.ToInt32(CurrentRow["PoPk"]) != 0) && (_txn0004ConCode == 1 || _txn0005ConCode == 1) || _txn0001ConCode == 0)
            {

                if (DtChildTransaction.Select("ItemCode <>'' AND (PurPrice<=0.00 Or qty <=0.00)").Length > 0)
                {
                    var messageResult = messageService.ShowMessage(MessageText.InvalidGridRecordOmit, MessageTitle, MessageType.QuizOKCancel);

                    if (messageResult == MessageBoxResult.No)
                    {
                        this.IsValid = false;
                        return;
                    }

                }
            }

            if (DtChildTransaction.Select("ItemCode<>'' AND (PurPrice> 0.00 AND qty >0.00)").Length == 0)
            {
                messageService.ShowMessage(MessageText.NoValidData, MessageTitle, MessageType.InfoOK);
                this.IsValid = false;
                return;
            }

            for (int i = DtChildTransaction.Rows.Count - 1; i >= 0; i--)
            {
                if (string.IsNullOrEmpty(DtChildTransaction.Rows[i]["ItemCode"].ToString()) || (DtChildTransaction.Rows[i]["Qty"]) == DBNull.Value || (DtChildTransaction.Rows[i]["PurPrice"]) == DBNull.Value)
                    DtChildTransaction.Rows[i].Delete();
            }
            DtChildTransaction.AcceptChanges();

            CalculateAmounts();

            if (_txn0016ConCode == 1)
            {
                var supplierRules = new SupplierRuleService();
                if (!supplierRules.CheckSupplierCreditLimit(Convert.ToInt32(CurrentRow["SupplierPk"]), Convert.ToDateTime(CurrentRow["TxnDate"]),
                    Convert.ToDouble(CurrentRow["TotalAmt"]), Convert.ToInt32(CurrentRow["CurPk"]), Convert.ToDouble(CurrentRow["CurRate"])))
                {
                    this.IsValid = false;
                    return;
                }
            }


           

            int poType = Convert.ToInt32(CurrentRow["PoType"]);

            if (FormMode == Modes.New)
            {
                RefGenCode = "SGRNT";
            }
            else
            {
                switch (poType)
                {
                    case 1:
                        RefGenCode = "SGRNL";
                        break;
                    case 2:
                        RefGenCode = "SGRNS";
                        break;
                    case 3:
                        RefGenCode = "SGRNA";
                        break;
                }
            }

            double currencyRate = Convert.ToDouble(CurrentRow["CurRate"]);
            double creditAmount = Convert.ToDouble(CurrentRow["TotalAmt"]);
            CurrentRow["TxnType"] = "11";
            CurrentRow["BTotalDis"] = Math.Round(Convert.ToDouble(CurrentRow["TotalDis"]) * currencyRate, 2);
            CurrentRow["BTotalTax"] = Math.Round(Convert.ToDouble(CurrentRow["TotalTax"]) * currencyRate, 2);
            CurrentRow["BTotalAmt"] = Math.Round(creditAmount * currencyRate, 2);
            CurrentRow["RefNo2"] =Convert.ToString(CurrentRow["RefNo"]);


            foreach (DataRow drDataDetail in DtChildTransaction.Rows)
            {
                drDataDetail["TxnDate"] = CurrentRow["TxnDate"];
                drDataDetail["BalQty"] = drDataDetail["Qty"];
                drDataDetail["TxnType"] = "11";

            }

            this.IsValid = true;
        }

        protected override void PostDataValidateExecuted(object obj)
        {
            if (!PrepareDataForApproveProcess())
            {
                this.IsValid = false;
            }
          
        }
        protected override void RefreshExternalDataObjectsExecueted(object obj)
        {
            base.RefreshExternalDataObjectsExecueted(obj);
          
            if (FormMode == Modes.New || FormMode == Modes.Edit || FormMode == Modes.Approve || FormMode == Modes.Delete)
            {
                ParentTableName = "fGrnTHed";
                ChildTableName = "fGrnTDet";
                _hasHedSaveFailed = false;
            }

            if (FormMode == Modes.New)
            {
                var masterReadService = new MasterReadService();
                CurrentRow["TxnDate"] = DateTime.Now;

                CurrentRow["POType"] = 1;
                CurrentRow["CurPk"] = masterReadService.GetCurrencyKey(GlobalVariables.BaseCurrency);
                CurrentRow["CurRate"] = 1.00;

                var commonReadService = new CommonReadService();
                CurrentRow["CostPk"] = commonReadService.GetUserWiseCostCenter();
                CurrentRow["LocationPk"] = commonReadService.GetUserWiseLocation();
                OnPropertyChanged("CurrentRow");
            }

            if (FormMode != Modes.None)
            {
                var transactionReadService = new TransactionReadService();
                int primaryKey = (CurrentRow["GrnPk"] == DBNull.Value ? 0 : Convert.ToInt32(CurrentRow["GrnPk"]));
                _dtGrnTax = transactionReadService.GetGoodReceiveTaxData(primaryKey);

                _dtGrnImExp = transactionReadService.GetGoodReceiveImportExpense(primaryKey);

                _dtCCrNote = transactionReadService.GetGrnCreditNotes(primaryKey);
            }

        }
        
        protected override void AddAddionalReportParametersExecuted(object obj)
        {
            base.AddAddionalReportParametersExecuted(obj);

            if (AdditionalReportParameters == null)
            {
                AdditionalReportParameters = new List<IReportParameters>();
            }

            AdditionalReportParameters.Add(new ReportParameters() { ParameterIndex = 8, ParameterName = "VatCompanyTaxNo", InputValue = GlobalVariables.VatCompanyTaxNo });
        }

        protected override void SetDataSourcesAndProperties()
        {
            var masterReadService = new MasterReadService();
            _txn0002ConCode = masterReadService.GetConCodeStatusDetails("TXN0002");

            // This need to be appied to the txtReferenceNo text box
            RefNoFilterExpression = (_txn0002ConCode == 1) ? "Appstat=2" : "Appstat=0";

            _txn0001ConCode = masterReadService.GetConCodeStatusDetails("TXN0001");

            // This need to be appied to the txtReferenceNo text box
            if (_txn0001ConCode == 1)
            {
                IsPurchaseOrderNoVisible = Visibility.Visible;
                IsPurchaseOrderNoMandatory = true;
            }
            else
            {
                IsPurchaseOrderNoVisible = Visibility.Collapsed;
                IsPurchaseOrderNoMandatory = false;
            }

            _txn0004ConCode = masterReadService.GetConCodeStatusDetails("TXN0004");

            _txn0003ConCode = masterReadService.GetConCodeStatusDetails("TXN0003");

            _txn0005ConCode = masterReadService.GetConCodeStatusDetails("TXN0005");

            _txn0016ConCode = masterReadService.GetConCodeStatusDetails("TXN0016");

            var transactionReadService = new TransactionReadService();
            _dtPoHeader = transactionReadService.GetPurchaseOrderDetails(1);
            _chkTxnDate = Convert.ToDateTime(_dtPoHeader.Rows[0]["TxnDate"]);
            BlockBackDatedTransaction = true;
            ParentTableName = "fGrnTHed";
            ChildTableName = "fGrnTDet";

        }

        protected override void EnableDisableSpecificControls()
        {
            base.EnableDisableSpecificControls();

            if (GlobalVariables.SystemCurrency.Trim().ToUpper() == "LOCAL")
            {
                IsCurrencyCodeEnabled = false;
                IsExchangeRateEnabled = false;
            }
            else
            {
                IsCurrencyCodeEnabled = IsExchangeRateEnabled = ((FormMode == Modes.New || FormMode == Modes.Edit) ? true : false);
                IsPurchaseOrderNoEnabled = (FormMode == Modes.Edit || FormMode == Modes.None) ? false : true;
                IsRemarksEnabled = IsTaxComcodeEnabled = (FormMode == Modes.Approve || FormMode == Modes.Edit || FormMode == Modes.New) ? true : false;

            }
        }

        protected override void PostDataInsertExecuted(object obj)
        {
            var transactionWriteService = new TransactionWriteService();

            var sqlTran = this.SqlTran;
            if (!transactionWriteService.UpdateGoodReceiveSpecificData(CurrentRow, _dtCCrNote,_dtGrnImExp,_dtGrnTax, ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }

        protected override void PostDataUpdateExecuted(object obj)
        {
            var transactionWriteService = new TransactionWriteService();
            var sqlTran = this.SqlTran;
            if (!transactionWriteService.UpdateGoodReceiveSpecificData(CurrentRow, _dtCCrNote,_dtGrnImExp,_dtGrnTax, ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }

        protected override void PreDataDeleteExecuted(object obj)
        {
            var transactionWriteService = new TransactionWriteService();
            var sqlTran = this.SqlTran;
            if (!transactionWriteService.DeleteGoodReceiveSpecificData(Convert.ToInt32(CurrentRow["GrnPk"]), Convert.ToString(CurrentRow["RefNo2"]), ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }

        }

        private void CalculateAmountsExecuted(object obj)
        {
            CalculateAmounts();
        }

        private void CalculateAmounts()
        {
            double curRate = Convert.ToDouble(CurrentRow["CurRate"]);
            string itemCode;
            double purchasePrice, costPrice, quantity, totalValue, totalBValue, totalDiscount, totalBDiscount, discount, total, totalB, sumTotalDiscount, sumTotal;
            double totalTax, totAmount;
            totalTax = totAmount = 0.00;

            int noOfDecimalPlaces = GlobalVariables.CurValDecimalPoints;
            int noOfAvgRateDecimal = GlobalVariables.AverageRateDecimal;


            int sequenceNo = 1;
            sumTotalDiscount = sumTotal = 0.00;
            foreach (DataRow drDataRow in DtChildTransaction.Rows)
            {
                itemCode = Convert.ToString(drDataRow["ItemCode"]);
                purchasePrice = (drDataRow["PurPrice"] == DBNull.Value ? 0.00 : Convert.ToDouble(drDataRow["PurPrice"]));

                quantity = (drDataRow["Qty"] == DBNull.Value ? 0.00 : Convert.ToDouble(drDataRow["Qty"]));
                discount = (drDataRow["DisPer"] == DBNull.Value ? 0.00 : Convert.ToDouble(drDataRow["DisPer"]));

                if (itemCode == string.Empty || purchasePrice == 0.00 || quantity == 0.00)
                {
                    drDataRow["DisAmt"] = 0.00;
                    drDataRow["BDisAmt"] = 0.00;
                    drDataRow["Amt"] = 0.00;
                    drDataRow["BAmt"] = 0.00;
                    drDataRow["SeqNo"] = 0;
                    drDataRow["CostPrice"] = 0.00;
                    continue;
                }

                drDataRow["CostPrice"] = Convert.ToDecimal(string.Format("{0:F2}", purchasePrice * curRate));

                costPrice = (drDataRow["CostPrice"] == DBNull.Value ? 0.00 : Convert.ToDouble(drDataRow["CostPrice"]));
                totalValue = Math.Round(quantity * purchasePrice, noOfDecimalPlaces);
                totalBValue = Math.Round(quantity * costPrice, noOfDecimalPlaces);
                totalDiscount = Math.Round((totalValue * discount) / 100, noOfDecimalPlaces);
                totalBDiscount = Math.Round(totalDiscount * curRate, noOfDecimalPlaces);

                total = Math.Round(totalValue - totalDiscount, noOfDecimalPlaces);
                totalB = Math.Round(totalBValue - totalBDiscount, noOfDecimalPlaces);

                drDataRow["DisAmt"] = totalDiscount;
                drDataRow["BDisAmt"] = totalBDiscount;
                drDataRow["Amt"] = total;
                drDataRow["BAmt"] = totalB;
                drDataRow["SeqNo"] = sequenceNo;
                sequenceNo += 1;
                sumTotalDiscount += totalDiscount;
                sumTotal += total;
            }


            CommonRules commonRulesObj = new CommonRules();
            totalTax = totAmount = 0.00;
            DataView viewChildTran = new DataView(DtChildTransaction);

            DataTable dtCopyChildTransaction = viewChildTran.ToTable("dtCopyChildTransaction", false, "GrnPk", "ItemPk", "Amt", "TaxComPk",  "PurPrice", "Qty","BAmt","TaxAmt","BTaxAmt");
            for (int i = dtCopyChildTransaction.Rows.Count - 1; i >= 0; i--)
            {
                if ((dtCopyChildTransaction.Rows[i]["ItemPk"] == DBNull.Value) || (dtCopyChildTransaction.Rows[i]["Qty"]) == DBNull.Value || (dtCopyChildTransaction.Rows[i]["PurPrice"]) == DBNull.Value)
                    dtCopyChildTransaction.Rows[i].Delete();
            }
            dtCopyChildTransaction.AcceptChanges();
            
            dtCopyChildTransaction.Columns.Add("RefNo1",typeof(Int32));
            DataView viewGrnTax= new DataView(_dtGrnTax);

            DataTable dtCopyGrnTax = viewGrnTax.ToTable("dtCopyGrnTax", false, "GrnPk", "ItemPk", "TaxComPk","TaxPk", "TaxPer", "TaxRate", "Taxseq", "TaxDetAmt", "BTaxDetAmt");

            if (FormMode == Modes.New || FormMode == Modes.Edit || FormMode == Modes.Approve)
            {
                bool isSuccess = commonRulesObj.MultipleLineTaxCalculation(dtTranDet: ref dtCopyChildTransaction, dtTaxDetailTable: ref dtCopyGrnTax, curRate: Convert.ToDouble(CurrentRow["CurRate"]), whereCondition: "ItemPk<>0 AND PurPrice <> 0.00 AND qty <>0.00", keyFields: "ItemPk", totalTax: out totalTax, totAmount: out totAmount);

            }
            else
            {
                bool isSuccess = commonRulesObj.MultipleLineTaxCalculation(dtTranDet: ref  dtCopyChildTransaction, dtTaxDetailTable: ref dtCopyGrnTax, curRate: Convert.ToDouble(CurrentRow["CurRate"]), whereCondition: "ItemPk<>0 AND PurPrice <> 0.00 AND qty <>0.00", keyFields: "ItemPk", totalTax: out totalTax, totAmount: out totAmount, referenceNo: Convert.ToInt32(CurrentRow["GrnPk"]), taxDetailTranTable: "fGrnTaxDt");
            }

            if (GlobalVariables.SystemCurrency == "FOREIGN")
            {
                CalculateImportExpense();
            }
            CurrentRow["TotalTax"] = totalTax;
            CurrentRow["TotalAmt"] = totAmount;
            CurrentRow["TotalDis"] = sumTotalDiscount;
            this.OnPropertyChanged("CurrentRow");
        }


        private void CurrencyCodeLostFocusExecuted(object obj)
        {
            TxtCurrency txtCurrency = (TxtCurrency)obj;
            if (txtCurrency.CurrencyCode != string.Empty)
            {
                CalculateAmounts();
            }
        }
        private void CalculateImportExpense()
        {

            var rowsToDelete = from r1 in _dtGrnImExp.AsEnumerable()
                               join r2 in DtChildTransaction.AsEnumerable()
                                    on r1.Field<Guid>("ItemCode") equals r2.Field<Guid>("ItemCode")
                               select r1;

            bool isNotFound = false;
            foreach (DataRow drGrnImp in _dtGrnImExp.Rows)
            {
                isNotFound = false;
                foreach (DataRow drValidRows in rowsToDelete)
                {
                    if (drGrnImp["ItemCode"] == drValidRows["ItemCode"])
                    {
                        isNotFound = true;
                        continue;
                    }
                    if (!isNotFound)
                    {
                        drGrnImp.Delete();
                    }
                }
            }

            double totalExp = (_dtGrnImExp != null && _dtGrnImExp.Rows.Count != 0 ? Convert.ToDouble(_dtGrnImExp.Compute("Sum(expdetamt)", "")) : 0);

        }

        private bool CheckTaxSCombinationStatus()
        {
            var masterReadService = new MasterReadService();
            var messageService = new MessageService();
            foreach (DataRow drGridData in DtChildTransaction.Rows)
            {
                string taxComCode = Convert.ToString(drGridData["TaxComCode"]);

                if (taxComCode == string.Empty)
                {
                    continue;
                }
                else
                {
                    if (!masterReadService.IsTaxCombinationActive(Convert.ToInt32(drGridData["TaxComPk"])))
                    {
                        messageService.ShowMessage("Inactive tax combination is selected. Please change to enter transactions. Tax Combination Code:" + taxComCode, MessageType.InfoOK);
                        return false;
                    }
                }

            }
            return true;
        }

        private bool CheckItemStatus()
        {
            var masterReadService = new MasterReadService();
            var messageService = new MessageService();
            foreach (DataRow drGridData in DtChildTransaction.Rows)
            {
                string itemCode = Convert.ToString(drGridData["ItemCode"]);

                if (itemCode == string.Empty)
                {
                    continue;
                }
                else
                {
                    if (!masterReadService.IsItemActive(Convert.ToInt32(drGridData["ItemPk"])))
                    {
                        messageService.ShowMessage("Inactive item is selected. Please change to enter transactions.\nItem Code:" + itemCode, MessageType.InfoOK);
                        return false;
                    }
                }

            }
            return true;
        }

        private bool PrepareDataForApproveProcess()
        {
            var messageService = new MessageService();

            if (FormMode == Modes.Approve || (_hasHedSaveFailed == true && FormMode == Modes.New))
            {
                MessageBoxResult result = messageService.ShowMessage(MessageText.ApproveEntry, MessageType.QuizYesNo);

                if (result == MessageBoxResult.Yes)
                {
                    _hasHedSaveFailed = true;
                    _txnTransactionType = Modes.Approve;
                    FormMode = Modes.New;

                    CurrentRow["PrtCopy"] = 0;
                    CurrentRow["RecordId"] = 0;

                    ChildTableName = "fGrnDet";
                    ParentTableName = "fGrnHed";
                    _dtCCrNote.Clear();
                    DataRow drCCrNote = _dtCCrNote.NewRow();
                    drCCrNote["ManuRef"] = CurrentRow["ManuRef"];
                    drCCrNote["TxnType"] = "10";
                    drCCrNote["TxnDate"] = CurrentRow["TxnDate"];
                    drCCrNote["SupplierPk"] = CurrentRow["SupplierPk"];
                    drCCrNote["CurPk"] = CurrentRow["CurPk"];
                    drCCrNote["CurRate"] = CurrentRow["CurRate"];
                    double creditAmount = Convert.ToDouble(CurrentRow["TotalAmt"]);
                    double currencyRate = Convert.ToDouble(CurrentRow["CurRate"]);
                    drCCrNote["Amt"] = creditAmount;
                    drCCrNote["TotBal"] = creditAmount;
                    drCCrNote["BAmt"] = creditAmount * currencyRate;
                    drCCrNote["GlPost"] = "Y";
                    drCCrNote["AddUser"] = GlobalVariables.LoggedInUser;
                    drCCrNote["AddDate"] = DateTime.Now;
                    drCCrNote["AddMach"] = Environment.MachineName + "#" + Environment.UserName;
                    _dtCCrNote.Rows.Add(drCCrNote);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
               
                RefGenCode = "SGRNT";
            }

            return true;
        }

        private void ItemCodeLostFocusExecuted(object obj)
        {
            if (FormMode == Modes.View || FormMode == Modes.Cancel || FormMode == Modes.Print)
            {
                return;
            }
            DtChildTransaction.AcceptChanges();
            TxtItem itemTextBox = (TxtItem)obj;
            string itemCode = itemTextBox.ItemCode.Trim();
            var masterReadService = new MasterReadService();
            var messageService = new MessageService();
            if (itemCode != string.Empty)
            {
                if (DtChildTransaction.Select("ItemCode='" + itemCode + "'").Length > 1)
                {

                    messageService.ShowMessage(MessageText.ItemCodeDuplicated, MessageTitle, MessageType.InfoOK);

                    DtChildTransaction.Rows[ItemRowIndex]["ItemPk"] = 0;
                    DtChildTransaction.Rows[ItemRowIndex]["ItemCode"] = string.Empty;
                    DtChildTransaction.Rows[ItemRowIndex]["ItemName"] = string.Empty;
                    DtChildTransaction.Rows[ItemRowIndex]["Qty"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["Amt"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["PurPrice"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["CostPrice"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["DisPer"] = 0.00;
                    DtChildTransaction.Rows[ItemRowIndex]["TaxComCode"] = string.Empty;
                    this.OnPropertyChanged("DtChildTransaction");
                    return;
                }

                // check the itemStatus
                if (itemTextBox.ItemCode != string.Empty)
                {
                    if (Convert.ToInt16(itemTextBox.ItemStatus) == 0)
                    {
                        messageService.ShowMessage(MessageText.InactiveItemFound, MessageTitle, MessageType.InfoOK);
                        DtChildTransaction.Rows[ItemRowIndex]["ItemPk"] = 0;
                        DtChildTransaction.Rows[ItemRowIndex]["ItemCode"] = string.Empty;
                        DtChildTransaction.Rows[ItemRowIndex]["ItemName"] = string.Empty;
                        DtChildTransaction.Rows[ItemRowIndex]["Qty"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["Amt"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["PurPrice"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["CostPrice"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["DisPer"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["TaxComPk"] = string.Empty;
                        DtChildTransaction.Rows[ItemRowIndex]["TaxComCode"] = string.Empty;
                        this.OnPropertyChanged("DtChildTransaction");
                        return;
                    }
                    else
                    {
                        if (Convert.ToString(DtChildTransaction.Rows[ItemRowIndex]["TaxComCode"]).Trim() == string.Empty)
                        {
                            DtChildTransaction.Rows[ItemRowIndex]["TaxComPk"] = (CurrentRow["TaxComPk"] == DBNull.Value ? 0 : Convert.ToInt32(CurrentRow["TaxComPk"]));
                            DtChildTransaction.Rows[ItemRowIndex]["TaxComCode"] = (CurrentRow["TaxComPk"] == DBNull.Value ? "" : masterReadService.GetTaxCombinationCode(Convert.ToInt32(CurrentRow["TaxComPk"])));

                        }
                    }

                    if (itemCode != _previousItemCode)
                    {
                        DtChildTransaction.Rows[ItemRowIndex]["PurPrice"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["CostPrice"] = 0.00;
                        DtChildTransaction.Rows[ItemRowIndex]["DisPer"] = 0.00;
                    }
                }
                               

                this.OnPropertyChanged("DtChildTransaction");
            }

        }
               

        private void RefreshCurrencyDataExecuted(object obj)
        {
            TxtCurrency txtCurrency = (TxtCurrency)obj;
            CurrentRow["CurRate"] = txtCurrency.CurrencyRate;
            this.OnPropertyChanged("CurrentRow");
        }



    }
}


